package com.atguigu.juc.juc20210301;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket //资源类 ,类就是一个实体对象的高度抽象封装体(类 = field + method)
{
    int number = 50;

    /*public synchronized void sale()
    {
        if(number > 0)
        {
            System.out.println(Thread.currentThread().getName()+"\t"+"卖出第:"+(number--)+"\t还剩下"+number);
        }
    }*/

    //new juc的学习一下

    Lock lock = new ReentrantLock();//可重入锁+独占锁+默认非公平锁

    public void sale()
    {
        lock.lock();
        try
        {
            if(number > 0)
            {
                System.out.println(Thread.currentThread().getName()+"\t"+"卖出第:"+(number--)+"\t还剩下"+number);
            }
        }finally {
            lock.unlock();
        }
    }


}

/**
 * @auther zzyy
 * @create 2020-03-25 12:41
 * 三个售票员    卖出      50张票
 * 如何编写企业级需要的工程化代码？
 * 1    线程  操作  资源类
 *    * 高内聚，低耦合OOP
 *
 *    第一步：直接新建资源类
 */
public class SaleTicketDemo
{
    public static void main(String[] args)//一切程序的入口
    {
        Ticket ticket = new Ticket();

        new Thread(() -> { for (int i = 1; i <=51 ; i++) ticket.sale(); },"t1").start();
        new Thread(() -> { for (int i = 1; i <=51 ; i++) ticket.sale(); },"t2").start();
        new Thread(() -> { for (int i = 1; i <=51 ; i++) ticket.sale(); },"t3").start();
    }
}
